package com.pjhouse.pipeline.context;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pjhouse.core.user.domain.UserDTO;

public class CookieUtil {

	public static int ONE_HOUR = 3600;

	public static int ONE_DAY = 3600 * 24;

	public static int ONE_WEEK = 3600 * 24 * 7;		//一周,为测试先改成一天

	public static int ONE_MONTH = 3600 * 24 * 30;

	public static Cookie getCookie(HttpServletRequest request, String name) {
		Cookie cookies[] = request.getCookies();
		if (cookies == null || name == null || name.length() == 0) {
			return null;
		}
		for (int i = 0; i < cookies.length; i++) {
			if (name.equals(cookies[i].getName())) {
				return cookies[i];
			}
		}
		return null;
	}

	public static String getCookieValue(HttpServletRequest request, String name) {
		Cookie cookie = getCookie(request, name);
		if (cookie != null) {
			return cookie.getValue();
		}
		return null;
	}

	public static void addCookie(
			HttpServletResponse response, Cookie cookie) {
		if (cookie != null) {
			cookie.setMaxAge(-1);
			cookie.setDomain("pjhouse.com");
			cookie.setPath("/");
			response.addCookie(cookie);
		}
	}

	public static void deleteCookie(
			HttpServletResponse response, Cookie cookie) {
		if (cookie != null) {
			cookie.setMaxAge(0);
			cookie.setDomain("pjhouse.com");
			cookie.setPath("/");
			cookie.setValue("");
			response.addCookie(cookie);
		}
	}

	public static void deleteCookie(
			HttpServletResponse response, String cookieName) {
		Cookie cookie = new Cookie(cookieName, null);
		if (cookie != null) {
			cookie.setMaxAge(0);
			cookie.setDomain("pjhouse.com");
			cookie.setPath("/");
			cookie.setValue("");
			response.addCookie(cookie);
		}
	}

	private static void setCookie(
			HttpServletResponse response, String name, String value) {
		setCookie(response, name, value, ONE_WEEK);
	}

	private static void setCookie(
			HttpServletResponse response, String name, String value, int maxAge) {
		Cookie cookie = new Cookie(name, value == null ? "" : value);
		cookie.setMaxAge(maxAge);
		cookie.setDomain("pjhouse.com");
		cookie.setPath("/");
		response.addCookie(cookie);
	}
	
	public static void setCookie(HttpServletResponse response, UserDTO user){
		setCookie(response, LoginContextHolder.ATTR_LOGIN, "1");
		setCookie(response, LoginContextHolder.ATTR_LOGIN_LAST, new Date().getTime() + "");
		setCookie(response, LoginContextHolder.ATTR_USER_ID_NUM, user.getId() + "");
		setCookie(response, LoginContextHolder.ATTR_USER_NAME, user.getName());
		setCookie(response, LoginContextHolder.ATTR_USER_ROLE, user.getRole());
	}

}
